from s_server.models import *
import torch
from s_server.tools.pdf_list import get_pdf_list


def get_code_info(code):
    res = Record.objects.filter(dm_id__dm=code).order_by("d")
    # print(res)
    # for data in res:
    #     print(data.zd)
    return res


def last_count_info(code, count=30):
    res = get_code_info(code)
    zd_list = [float(data.zd) / 100 for data in res]
    zd_list = zd_list[-count:]
    return zd_list

#
def get_P_and_Q(zd_list, count=30, a_times=1.0, b_times=1.0):
    # print("zd_list",zd_list)

    epsilon = 1e-9
    t_count = 0
    t_zd_all = 1
    f_zd_all = -1

    zd_list = zd_list[-count:]
    for i in zd_list:
        if float(i) > 0:
            # print(i, "t_zd_all", "11111")
            t_zd_all = t_zd_all * (1 + float(i))
            t_count += 1
        else:
            # print(i, "f_zd_all", "22222")
            f_zd_all = f_zd_all * (1 - float(i))
    p = round(t_count / len(zd_list), 6)
    q = round(1 - p, 6)
    # a = 0.10
    # b = 0.05
    a = (1 - f_zd_all) * a_times + epsilon
    b = (1 + t_zd_all) * b_times + epsilon
    # a = -(f_zd_all / (len(zd_list) - t_count) / 100)  + epsilon
    # b = t_zd_all / t_count / 100 + epsilon
    # 极值位置
    kl_data = round((p / a - q / b), 9)
    # print("code={} p={} q={} a={} b={} count={} {} {}".format(code, p, q, a, b, count, zd_list,kl_data))
    return a, b, p, q, kl_data

# 按照测算的天数和涨跌值来计算一个综合的投资比例
def get_code_kl_state(kl_days_list,zd_list, a_times, b_times):
    print("计算的天数",kl_days_list)
    pdf_list = get_pdf_list(kl_days_list)
    print("按照计算天数来计算占比",pdf_list)
    code_lk_states = []
    if len(zd_list) != kl_days_list[0]:
        return -1000.0
    for j in kl_days_list:
        code_lk_states.append((get_P_and_Q(zd_list, j, a_times, b_times)[4]))
    print("投资比例估算",code_lk_states)
    final_state = (torch.FloatTensor(code_lk_states) @ torch.FloatTensor(pdf_list).t()).item()
    print("综合投资比例", final_state)
    return final_state



# def get_code_kl_states(codes):
#     code_kl_state_dict = {
#     }
#     kl_days_list = [120, 90, 60, 30, 15, 10, 5]
#     for code in codes:
#         print("code", code)
#         zd_list = last_count_info(code, kl_days_list[0])
#         code_kl_state_dict[code] = get_code_kl_state(zd_list)
#     return code_kl_state_dict

# from scipy.stats import poisson
# import torch
# mu_list = [120, 90, 60, 30, 15, 10, 5]
# # 定义λ（lambda）值
# mu = 10000
#
# p_list=[]
# for k in mu_list:
#     # 计算泊松分布的概率值
#     p = poisson.pmf(k, mu)
#     p_list.append(p)
#
#
# print(p_list)
# tensor = torch.FloatTensor(p_list)
# softmax_result = torch.softmax(tensor, dim=0)
# print(softmax_result)
#
# from scipy.stats import poisson
#
# # 定义λ（lambda）值
# mu = 0.1
# # 定义k值
# k = 0
# # 计算泊松分布的概率值
# p = poisson.pmf(k, mu)
# print(p)
